package com.tungse;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试线程池下InheritableThreadLocal线程变量失效的场景
 */
public class TestInheritableThreadLocal {

    private static final InheritableThreadLocal<String> ithreadLocal = new InheritableThreadLocal<>();
//    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    // 固定大小的线程池，保证线程复用
    private static final ExecutorService executorService = Executors.newFixedThreadPool(1);

    public static void main(String[] args) throws InterruptedException {
//        threadLocal.set("main线程 ThreadLocal 变量1");
        ithreadLocal.set("main线程 InheritableThreadLocal 变量1");
        // 正常取到 main线程 变量1
        executorService.execute(() -> {
            System.out.println(ithreadLocal.get());
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() +  ithreadLocal.get());

            },"内部子线程1").start();
            ithreadLocal.set("子线程修改测试 InheritableThreadLocal");
            System.out.println(ithreadLocal.get());

            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() +  ithreadLocal.get());

            },"内部子线程2").start();
        });
        Thread.sleep(1000);
        System.out.println(ithreadLocal.get());
//        threadLocal.set("main线程 ThreadLocal 变量2");
        ithreadLocal.remove();
        ithreadLocal.set("main线程 InheritableThreadLocal 变量2");
        // 线程复用再取还是 main线程 变量1
        executorService.execute(() -> {
            System.out.println(ithreadLocal.get());
        });
    }
}